package com.ysd.lis.util.qcrule;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ATRule extends Rule{
    public ATRule(String id, String name, int a, int n, double l) {
        super(id, name, a, n, l);
        this.type = RuleType.AXRule;
    }

    @Override
    public RuleStatement Evaluate(QCResult result) {


        //if (result.Results.Count < A)
        if(result.getResults().size() <a )
        {
            return RuleStatement.DISABLE;
        }

        List<Result> results = result.getResults();
        //var items = result.Results.GetRange(result.Results.Count - A, A);
        List<Result> items = new ArrayList<>();
        for(int i = 0 ;i< a; i++){
            items.add(results.get(results.size()-a+i));
        }

        if (HasEmptyResult(items))
        {
            return RuleStatement.DISABLE;
        }

//        var hs = new List<Result>();
        List<Result> hs = new ArrayList<>();
//        var ls = new List<Result>();
        List<Result> ls = new ArrayList<>();
        //递增递减数据
//        items.Aggregate((current, next) =>
//        {
//            if (!hs.Any() || current.Z < hs.Last().Z)
//            {
//                hs.Add(current);
//            }
//
//            if (!ls.Any() || current.Z > ls.Last().Z)
//            {
//                ls.Add(current);
//            }
//
//            return next;
//        });

        for(int i = 0;i<items.size();i++){
            //234256
            //if (!hs.Any() || current.Z < hs.Last().Z)
            if(CollectionUtils.isEmpty(hs)||items.get(i).getZvalue()<hs.get(hs.size()-1).getZvalue())
            {
                hs.add(items.get(i));
            }

            //if (!ls.Any() || current.Z > ls.Last().Z)
            if(CollectionUtils.isEmpty(ls)||items.get(i).getZvalue()>hs.get(hs.size()-1).getZvalue())
            {
                ls.add(items.get(i));
            }
        }


        if (hs.size() >= a || ls.size() >= a)
        {
            items.get(items.size()-1).setIsOutControl(true);

            items.get(items.size()-1).getOutControlInfos().add(new OutControlInfo(id,false,
                    hs.size()>=a?hs.stream().map(Result::getId).collect(Collectors.toList()) : ls.stream().map(Result::getId).collect(Collectors.toList())));
//            {
//                RuleId = Id,
//                IsMutiMaterial = false,
//                MemberIds = hs.Count() >= A ? hs.Select(p => p.Id).ToList() : ls.Select(p => p.Id).ToList()
//            });
            return RuleStatement.OK;
        }


        return RuleStatement.FAILED;
    }

    @Override
    public RuleStatement EvaluateMulti(List<QCResult> results) {
        return RuleStatement.DISABLE;
    }
}
